import type { FunctionsInterface } from '@/api/menu';
import { compact } from 'lodash-es';
import type { RouteRecordRaw } from 'vue-router';

export const firstLetterUpperCase = (str: string): string => {
  if (str.length === 0) {
    return str;
  }
  const firstLetter = str.charAt(0).toUpperCase();
  const restOfString = str.slice(1);

  return firstLetter + restOfString;
};

// /cpoe/pathologyApplicationForm
// -> pathologyApplicationForm
export const routePathParse = (str: string): string => {
  const strArr = compact(str.split(PATH_DIVIDE));
  if (strArr.length) {
    return strArr.splice(1).join('/');
  }

  return str;
};
export const routeNameParse = (str: string): string => {
  const strArr = compact(str.split('/'));
  if (strArr.length) {
    const name = strArr.pop() as string;
    return firstLetterUpperCase(name);
  }

  return str;
};

export const traverseMenu = (
  menus: FunctionsInterface[],
  callback: (menu: FunctionsInterface) => void,
) => {
  for (const menu of menus) {
    callback(menu);
    if (menu.children) {
      traverseMenu(menu.children, callback);
    }
  }
};

export const genRoutes = () => {
  const routes = [] as RouteRecordRaw[];
  const appId = useMicroAppStore()?.currentApp?.id;
  if (appId) {
    const normalMenu = useMenuStore().menu[appId].normalMenu;
    if (Array.isArray(normalMenu)) {
      traverseMenu(normalMenu, (func: FunctionsInterface) => {
        if (func.funcType === FuncTypeEnum.MENU) {
          const path = `${routePathParse(func.funcPath as string)}`;
          const route: RouteRecordRaw = {
            path: `/${path}`,
            name: `${routeNameParse(func.funcPath as string)}`,
            meta: {
              title: `${func.funcName}`,
            },
            component: () =>
              import(`../views/${firstLetterUpperCase(path)}/index.vue`),
          };
          routes.push(route);
        }
      });
    }
  }
  return routes;
};
